package cn.com.homeyoda.aimate.aihealth.ui.problem;

import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.FEEDBACK_SUCCESS;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.library.baseAdapters.BR;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wzq.mvvmsmart.utils.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.bean.FeedbackTypeBean;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityProblemBinding;

public class ProblemActivity extends BaseActivity<ActivityProblemBinding, ProblemModel> {

    private ProblemAdapter problemAdapter;
    // private CameraAdapter cameraAdapter;
    // private List<File> cameraList = new ArrayList<>();
    private List<FeedbackTypeBean.DataBean> typeList = new ArrayList<>();

    // private String  problem = "";

    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int PERMISSIONS_REQUEST_CODE = 100;
    private File photoFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    @Override
    public ProblemModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(ProblemModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.getFeedBackType();
        initRecyclerView();
    }

    private void initRecyclerView() {
        problemAdapter = new ProblemAdapter(R.layout.problem_item, typeList, getApplicationContext());
        binding.setLayoutManager(new GridLayoutManager(getApplicationContext(), 3));
        binding.setAdapter(problemAdapter);

//        cameraAdapter = new CameraAdapter(R.layout.camera_item,cameraList,getApplicationContext());
//        binding.setLayoutManager2(new GridLayoutManager(getApplicationContext(),3));
//        binding.setAdapter2(cameraAdapter);

        problemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                problemAdapter.toggleSelection(position);
                // problem = typeList.get(position);
                // Log.i("haha","problem====="+problem);
            }
        });

//        cameraAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                Log.i("haha","delete====="+position);
//                cameraList.get(position).delete();
//                cameraList.remove(position);
//                cameraAdapter.setNewData(cameraList);
//            }
//        });

        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                List<String> strings =  new ArrayList<>();
//                for (Integer position : problemAdapter.getSelectedItems()) {
//                    strings.add(stringList.get(position));
//                }
//                Log.i("haha","strings==="+strings.toString());
                finish();
            }
        });

//        binding.camera.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if(cameraList.size()<3){
//                    if (allPermissionsGranted()) {
//                        dispatchTakePictureIntent();
//                    } else {
//                        ActivityCompat.requestPermissions(ProblemActivity.this,
//                                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                                PERMISSIONS_REQUEST_CODE);
//                    }
//
//                }else{
//                    ToastUtils.showShort("最多拍三张");
//                }
//            }
//        });

        binding.upload.setOnClickListener(view -> {
            if (problemAdapter.getSelectedItems().isEmpty()) {
                ToastUtils.showShort("请选择反馈类型");
                return;
            }
            String desc = binding.edtDesc.getText().toString();
            if (TextUtils.isEmpty(desc) || desc.length() < 15) {
                ToastUtils.showShort("请填写15个字以上的描述");
                return;
            }
            String phone = binding.edtPhone.getText().toString();
            /*if (TextUtils.isEmpty(phone)) {
                ToastUtils.showShort("请填写微信或手机号码");
                return;
            }*/
            StringBuilder stringBuilder = new StringBuilder();
            for (Integer index : problemAdapter.getSelectedItems()) {
                if (!TextUtils.isEmpty(stringBuilder)) stringBuilder.append(",");
                stringBuilder.append(typeList.get(index).getId());
            }
            viewModel.uploadFeedBack(stringBuilder.toString(), desc, phone);
        });

    }

    private boolean allPermissionsGranted() {
        String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  // prefix
                ".jpg",         // suffix
                storageDir      // directory
        );

        // Save a file: path for use with ACTION_VIEW intents
        photoFile = image;

        // Return the file
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            try {
                photoFile = createImageFile();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            if (allPermissionsGranted()) {
                dispatchTakePictureIntent();
            } else {
                // Permission denied, show a message to the user.
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            if (photoFile != null && photoFile.exists()) {
                // cameraList.add(photoFile);
                // cameraAdapter.setNewData(cameraList);
            } else {
                // Handle the case where the file doesn't exist as expected
            }
        }
    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.feedbackType.observe(this, typeList -> {
            this.typeList = typeList;
            problemAdapter.setNewData(typeList);
        });

        LiveEventBus.get(FEEDBACK_SUCCESS, boolean.class).observe(this, aBoolean -> {
            finish();
        });

    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_problem;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
